$(document).ready(onCartpoolCartReady);

var searchAjaxRequest;
var saveAjaxRequest;
var listOffset = 0;
var lastFocussedPriceField;

function onCartpoolCartReady(){
	$('#searchbox').autofill();
	$('#searchbox').bind("keyup", onSearchChanged);
	
	accordionizeUl();
	
	handleShoppingListContainer();
}

function onDataSelected(){
	//ask the server for the shoppinglist, if one exists
	// it will return the exact data so the pretty data can show it correctly
		
}

function onCancelButtonClicked(event){
	hidePopup();
}

function onAddButtonClicked(event){
	$.post("/create_product/index/", 
			{ name:$('#popup_name')[0].value, category:$('#category_select')[0].value },
			onProductSaved
	);
}

function onProductSaved(){
	$('#searchbox')[0].value = $('#popup_name')[0].value;
	hidePopup();
	var event = new Object();
	event.target = new Object();
	event.target = $('#searchbox')[0]; 
	onSearchChanged(event);
}

function onSearchChanged(event){
	location.hash = "";
	
	try{
		searchAjaxRequest.abort();
	}catch(e){}

	if($('#productList li.no_products_found').length == 1){
		if(event.which == "13"){ //when pressed enter
			createNewProduct(event);
		}
	}
	
	searchAjaxRequest = $.post("/find_products/index/", 
			{ search:event.target.value },
			onProductsFound
	);	
}

function createNewProduct(event){
	try{
		event.preventDefault();
	}catch(e){}
	
	showPopup();
}

function showPopup(){
	$('#popup_addButton').bind("click", onAddButtonClicked);
	$('#popup_cancelButton').bind("click", onCancelButtonClicked);
	
	if($('#searchbox')[0].value == "Search..."){
	
	}else{
		$('#popup_name')[0].value = $('#searchbox')[0].value;
	}
	
	
	$('#popup').fadeIn(100);
	
	//set focus
	$('#popup_name')[0].focus();
}

function hidePopup(){
	$('#popup_addButton').unbind("click", onAddButtonClicked);
	$('#popup_cancelButton').unbind("click", onCancelButtonClicked);
	$('#popup').fadeOut(100);
}

function onProductsFound(data){
	$('#productList').html(data);
	
	// when no products are found
	if($('#productList li.no_products_found').length == 1){
		$('#addNewProductLink').removeClass("disabled");		

		$('#productList li.no_products_found a').bind("click", createNewProduct);
		$('#addNewProductLink').bind("click", createNewProduct);
		
		if(event.which == "13"){ //when pressed enter
			createNewProduct({});
		}
	}else{
		$('#addNewProductLink').addClass("disabled");	
		$('#productList li.no_products_found a').unbind("click", createNewProduct);
		$('#addNewProductLink').unbind("click", createNewProduct);
	}
	
	accordionizeUl();
}

function doNothing(event){}

function accordionizeUl(){
	if($('#productList li.no_products_found').length != 1){
		$('#productList ul').accordion();
		$('#productList ul p a').bind("click", onLinkInListClicked);
	}else{
		$('#addNewProductLink').removeClass("disabled");		

		$('#productList li.no_products_found a').bind("click", createNewProduct);
		$('#addNewProductLink').bind("click", createNewProduct);
	}
}

function onLinkInListClicked(event){
	event.preventDefault();
	var shoppingListId = $('#shoppingListId').text();
	var product = $(this).text();
	var rayon = $(this).parent().parent().prev().text();
	if(listOffset == null || listOffset == ""){
		listOffset = 0;		
	}
	$.post("/products_in_cart_handler/createProductInCart/" + listOffset, 
			{ shoppingListId:shoppingListId, product:product, rayon:rayon },
			onNewProductCreated
	);
}

function onNewProductCreated(data){
	$('#shoppinglist_container').html(data);
	handleShoppingListContainer();
}

function handleShoppingListContainer(){
	if(location.hash == "#paying"){
		setImPaying();
	}
	if($('#shoppingListClosed').text() != ""){
		setImPaying();
	}
	
	//$('div.comment textarea').autoResize({extraSpace : 0});
	$('div.comment textarea').focus(function(){
			if($(this).text() == "enter your comment here"){
				$(this).text("");
			}	
		}
	).blur(function(){
		if($(this).text() == ""){
		}	
	});
	
	
	if($('#datepicker').length > 0){
		var dateString = $('#datepicker').text();
		$('#datepicker').text(prettyDate(dateString));		
	}
	
	
	listOffset = $('#shoppingListOffset').text();
		
	$('#shoppinglist_container a.decreaseQty').bind("click", onDecreaseProductClicked);
	$('#shoppinglist_container a.increaseQty').bind("click", onIncreaseProductClicked);
	$('#shoppinglist_container a.addComments').bind("click", onAddCommentsClicked);
	$('#shoppinglist_container a.delete').bind("click", onDeleteProductClicked);
	$('#shoppinglist_container div.comment textarea').bind("change", onTextareaChanged);
	$('#shoppinglist_container div input.price').bind("change", onPriceChanged);
	
	
	$('#shoppinglist_container input.pay').bind("click", onPayClick);
	$('#shoppinglist_container input.close').bind("click", onCloseClick);
	//$('#shoppinglist_container input.print').bind("click", onPrintClick);
	$('#shoppinglist_container input.print').popupWindow({ 
		windowURL:"/printing/printList/" + listOffset, 
		windowName:'swip' 
		});

	$('a.previousList').bind("click", onPreviousClicked);
	$('a.nextList').bind("click", onNextClicked);
	
	/*
	$('#datepicker').datepick({showAnim:'slideDown', 
		duration:'fast', 
		alignment:'bottomRight', 
		mandatory:true,
		closeAtTop: false,
		changeYear: false,
		changeMonth:false,
		onSelect:onDataSelected
	});*/
	Cufon.replace('#shoppinglist_container h1');
	Cufon.now();
	$('img.loading_img').fadeOut();
	
	$('#shoppinglist_container div input.price').bind('focus', onPriceFieldGotFocus);
	if(lastFocussedPriceField){
		$('#shoppinglist_container div input.price[rel='+lastFocussedPriceField+']').focus();
		$('#shoppinglist_container div input.price[rel='+lastFocussedPriceField+']').select();
	}	
}

function onPriceFieldGotFocus(event){
	//alert("received: " + $(this).attr('rel'));
	lastFocussedPriceField = $(this).attr('rel');
}

function onPreviousClicked(){ 
	$('#shoppinglist_container').load("/products_in_cart_handler/loadShoppingList/" + (parseInt(listOffset)+1), onProductTotalPriceChanged);
	$('img.loading_img').fadeIn('fast');
}

function onNextClicked(){ 
	$('#shoppinglist_container').load("/products_in_cart_handler/loadShoppingList/" + (parseInt(listOffset)-1), onProductTotalPriceChanged);
	$('img.loading_img').fadeIn('fast');
}

function onCloseClick(event){
	event.preventDefault();
	location.hash = "";
	var listId = $(this).attr('rel');
	$('#shoppinglist_container').load("/products_in_cart_handler/closeShoppingList/" + listId + "/" + listOffset, onProductTotalPriceChanged);
	
	$('img.loading_img').fadeIn('fast');
}

function onPriceChanged(event){
	event.preventDefault();
	var productId = $(this).attr('rel');
	var price = event.target.value;
	
	
	$.post("/products_in_cart_handler/changePriceOnProduct/" + listOffset, 
			{ productId:productId, price:price },
			onProductTotalPriceChanged
	);
	
	$('img.loading_img').fadeIn('fast');
}

function onTextareaChanged(event){
	var productId = $(this).attr('rel');
	var comment = event.target.value;
	//if(comment != ""){
		$.post("/products_in_cart_handler/updateCommentOnProduct/" + listOffset, 
				{ productId:productId, comment:comment },
				onNewProductCreated
		);
	//}
	
	$('img.loading_img').fadeIn('fast');
}

function onPayClick(){
	location.hash = "paying";
	var listId = $(this).attr('rel');
	$('#shoppinglist_container').load("/products_in_cart_handler/setImPaying/" + listId + "/" + listOffset, onProductTotalPriceChanged);
	
	$('img.loading_img').fadeIn('fast');
}

function setImPaying(){
	/*$('#shoppinglist_container span.middle').css({width:"266px"});
	$('#shoppinglist_container span.price').show();
	$('#shoppinglist_container input.price').show();
	$('#shoppinglist_container div.total').show();
	$('#shoppinglist_container input.pay').hide();
	$('#shoppinglist_container input.close').show();*/
}

function onDecreaseProductClicked(event){
	event.preventDefault();
	var productId = $(this).attr('rel');
	
	$('#shoppinglist_container').load("/products_in_cart_handler/decreaseQtyOnProduct/" + productId + "/" + listOffset, handleShoppingListContainer);
	
	$('img.loading_img').fadeIn('fast');
}
function onIncreaseProductClicked(event){
	event.preventDefault();
	var productId = $(this).attr('rel');
	$('#shoppinglist_container').load("/products_in_cart_handler/increaseQtyOnProduct/" + productId + "/" + listOffset, handleShoppingListContainer);
	
	$('img.loading_img').fadeIn('fast');
}
function onAddCommentsClicked(event){
	event.preventDefault();
	var productId = $(this).attr('rel');
	$('#shoppinglist_container').load("/products_in_cart_handler/addCommentOnProduct/" + productId + "/" + listOffset, handleShoppingListContainer);
	
	$('img.loading_img').fadeIn('fast');
}
function onDeleteProductClicked(event){
	event.preventDefault();
	var productId = $(this).attr('rel');
	$('#shoppinglist_container').load("/products_in_cart_handler/deleteProductInCart/" + productId + "/" + listOffset, handleShoppingListContainer);
	
	$('img.loading_img').fadeIn('fast');
}

function onProductTotalPriceChanged(data){
	if(data){
		$('#shoppinglist_container').html(data);
		handleShoppingListContainer();
	}
	$('#userlist_container').load("/user_handler/getUsersInGroup/");
}